package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.IntoQueryAdapter;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.view.IntoQueryPopView;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshBase;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshListView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ScreenSwitch;
import com.eeepay.v2_library.view.TitleBar;

import java.util.Arrays;
import java.util.Map;

import cn.eeepay.api.grpc.nano.MerchantSearchProto;
import cn.eeepay.api.grpc.nano.MerchantSearchServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/4 0004.
 * 进件查询
 */
public class IntoQueryActivity extends ABBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener{

    private TitleBar titleBar;
    //    private TextView[] head;
    private PullToRefreshListView listView;
    private IntoQueryPopView popView;

    private IntoQueryAdapter adapter;//适配器
    private String state; // 状态

    private Map<String, String> params;

    private int currPage = 1;
    private int pageSize = 10;
    private int total = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_into_query;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        titleBar.setShowRight(View.VISIBLE);
        titleBar.setRightTextView("筛选");
        titleBar.setRightTextColor(R.color.unify_grounding_white);

        listView = getViewById(R.id.lv_into_content);

    }

    @Override
    protected void eventOnClick() {
        //筛选
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                goActivityForResult(IntoQueryFilterActivity.class, 0);
            }
        });

        adapter = new IntoQueryAdapter(mContext);
        listView.setAdapter(adapter);

        sendHttpRequest(0);
//        adapter.add(new IntoQueryInfo("9999999988888877777", "wtf", "138383843888",
//                "1", "洗浴", "2016-03-04 15:04:00", "长相不合格;人品不合格"));
//        adapter.add(new IntoQueryInfo("9999999988888877777", "wtf", "138383843888",
//                "2", "洗浴", "2016-03-04 15:04:00", "长相不合格;人品不合格"));
//        adapter.add(new IntoQueryInfo("9999999988888877777", "wtf", "138383843888",
//                "3", "洗浴", "2016-03-04 15:04:00", "长相不合格;人品不合格"));

        listView.setOnItemClickListener(this);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        //上下拉
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                currPage = 1;
                sendHttpRequest(0);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if(total > currPage * pageSize){
                    currPage++;
                    sendHttpRequest(0);
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SystemClock.sleep(1000);
                            showToast("已经是最后一页了");
                            if(listView.isRefreshing()){
                                listView.onRefreshComplete();
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        Intent intent = new Intent();
//        intent.putExtra("bpId", adapter.getItem(position).getBpId());
//        intent.putExtra("merNo", adapter.getItem(position).getMerNo());
        position --;
        Bundle bundle = new Bundle();
        bundle.putString(Constant.KEY.BP_ID, adapter.getItem(position).bpId);
        bundle.putString(Constant.KEY.MER_NO, adapter.getItem(position).merchantNo);
        Log.d("DataD", adapter.getItem(position).mobilephone + "  |  " + adapter.getItem(position).sn);
        bundle.putString(Constant.KEY.MER_PHONE, adapter.getItem(position).mobilephone);
        bundle.putString(Constant.KEY.SNO, adapter.getItem(position).sn);
        ScreenSwitch.switchActivity(this, DataDetailsActivity.class, bundle, 0);
    }

//    private void setEnabled(int x){
//        for (int i = 0; i < head.length; i++){
//            if(i == x){
//                head[i].setEnabled(false);
//            }else{
//                head[i].setEnabled(true);
//            }
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            this.params = (Map<String, String>) data.getSerializableExtra("into_filter");
            sendHttpRequest(0);
        }
    }


    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {

                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        MerchantSearchServiceGrpc.MerchantSearchServiceBlockingStub stub = MerchantSearchServiceGrpc.newBlockingStub(channel);
                        MerchantSearchProto.MerchantSearchRequest request = new MerchantSearchProto.MerchantSearchRequest();
                        if (params == null) {
                            request.id = -1;//状态
//                        request.merchantName = ;//商户名称
//                        request.agentNo = UserInfo.getInstance().getAgentNo();
                            request.agentNode = UserInfo.getInstance().getAgentNode();
                            request.includeSon = "1";
                            request.posType = "";
                            request.mobilephone = "";//手机号
                            request.bpId = "";//业务产品
                            request.createStartDate = "";
                            request.createEndDate = "";
                        } else {
                            request.merchantStatus = getParamString("status");//状态
                            request.merchantName = getParamString("merId");//商户名称
                            request.agentNo = UserInfo.getInstance().getAgentNo();
                            request.agentNode = UserInfo.getInstance().getAgentNode();
                            request.includeSon = getParamString("hasNext");
                            request.posType = getParamString("device");
                            request.mobilephone = getParamString("phone");//手机号
                            request.bpId = getParamString("product");//业务产品
                            request.createStartDate = getParamString("createTime");
                            request.createEndDate = getParamString("endTime");
                        }
                        request.page = currPage;
                        request.size = pageSize;
                        return stub.getMpageInfoRpc(request);
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        if(listView.isRefreshing()){
                            listView.onRefreshComplete();
                        }
                        dismissProgressDialog();
                        MerchantSearchProto.MerchantSearchResponse response = (MerchantSearchProto.MerchantSearchResponse) result;
                        if (result == null) {
                            showToast("查询失败");
                            return;
                        }
                        if (response.success) {
                            total = response.total;
                            //add by zhuangzeqin 2017年4月21日14:21:44 进件查询查不到的时候提示“暂没有找到您要的内容”
                            if (total==0)
                            {
                                showToast(response.msg);
                            }
                            if (currPage == 1) {
                                adapter.setList(Arrays.asList(response.merchantInfo));
                            } else {
                                adapter.addAll(Arrays.asList(response.merchantInfo));
                            }
                        } else {
                            showToast(response.msg);
                            Log.d("intoQuery", " response.msg-->" + response.msg);
                        }
                    }
                }
        );
    }

    private String getParamString(String key) {
        String value = params.get(key);
        if (TextUtils.isEmpty(value) || "全部".equals(value) || "请选择".equals(value)) {
            return "";
        }
        return value;
    }


}
